// console.log('------------',location.href);

// 获取全部参数
let getQueryParams = function() {
	let params = [];
	let query = window.location.search.substring(1);
	let vars = query.split("&");
	for (let i = 0, len = vars.length; i < len; i++) {
		let pair = vars[i].split("=");
		params[pair[0]] = pair[1];
	}
	return params;
};

// 获取某个参数
let getQueryParam = function(name, defaultValue) {
	params = getQueryParams();
	if (params[name]) {
		return params[name];
	}
	if (defaultValue !== null) {
		return defaultValue;
	}
	return null;
};

let formatTime = function(time) { //
	let date = new Date(time * 1000);
	let year = date.getFullYear();
	let month = (date.getMonth() + 1).toString().padStart(2, '0');
	let day = date.getDate().toString().padStart(2, '0');
	let hour = date.getHours().toString().padStart(2, '0');
	let minute = date.getMinutes().toString().padStart(2, '0');
	let second = date.getSeconds().toString().padStart(2, '0');
	return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
};

Vue.component('co-header', {
	data: function() {
		return {};
	},
	props: ['categoryId'],
	template: `<div class="cl-header container-fluid">
				<div class="header-content container">
					<nav class="navbar navbar-expand-lg navbar-light">
						<a class="navbar-brand" href="calmlog-index.html">
							<img src="img/logo.jpg" width="144" height="72" alt="">
						</a>
						<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav"
							aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
							<span class="navbar-toggler-icon"></span>
						</button>
						<co-header-nav :category-id="categoryId"></co-header-nav>
						
					</nav>
				</div>
			</div>
`
});

Vue.component('co-header-nav', {
	data: function() {
		return {
			category_id: 0,
			categoryList: []
		};
	},
	props: ['categoryId'], // 外围传递的categoryId
	created: function() {
		this.category_id = getQueryParam('category_id', 0); // 根据分类列表页面获取category_id参数
		if (this.categoryId > 0) {
			this.category_id = this.categoryId;
		}
		let _this = this;

		axios.get('http://localhost:8901/api/category/list/')
			.then(function(response) {
				if (response.data.status == 0) {
					_this.categoryList = response.data.data.categoryList;
				}
			})
			.catch(function(error) {
				console.log(error);
			});
	},
	watch: {
		categoryId: function(newValue) {
			console.log(1111, newValue);
			this.category_id = newValue;
		}
	},
	template: `<div class="collapse navbar-collapse justify-content-end" id="navbarNav">
				<ul class="navbar-nav">
					<li class="nav-item" v-bind:class="{active: !category_id}">
						<a class="nav-link" href="calmlog-index.html">首页 <span
								class="sr-only">(current)</span></a>
					</li>
					<li class="nav-item" v-for="item in categoryList" v-bind:class="{active: category_id==item.category_id}">
						<a class="nav-link" v-bind:href="'calmlog-list.html?category_id='+item.category_id">
							{{item.category_name}}
						</a>
					</li>
				</ul>
			</div>`
});

Vue.component('co-middle', {
	data: function() {
		return {
			articleList: [],
			category_id: 0,
			page: 1,
			page_size: 3,
			total: 20,
		};
	},
	created: function() {
		this.category_id = getQueryParam('category_id', 0);
		this.getArticleList(1);
	},
	methods: {
		getArticleList: function(page) {
			let _this = this;
			_this.page = page;
			$.ajax({
				url: "http://localhost:8901/api/article/list/",
				type: "GET",
				data: {
					page: page,
					page_size: this.page_size,
					category_id: this.category_id
				},
				beforeSend: function(xhr) {
					console.log("加载中...");
				},
				success: function(result) {
					console.log('--------', result);
					if (result.status == 0) { // 服务端成功处理
						_this.articleList = result.data.articleList;
						_this.total = result.data.total;
					} else {
						alert("获取文章列表失败，具体信息：" + result.message);
					}
				}
			});
		}
	},
	computed: {
		paginator: function() {
			let result = {
				range: 2, // 页码每边显示几条
				page: this.page, //  当前页
				page_size: this.page_size, // 每页显示几条记录
				total: this.total, // 总条目数
				pages: [] // 要显示的页码列表
			};
			result.count = result.range * 2 + 1; // 总的显示的分页数
			result.totalPage = Math.ceil(result.total / result.page_size); // 总页码数

			let temp = result.totalPage - result.page;
			let start = Math.max(1, (temp < 2) ? (result.page - (result.count - 1) + temp) : result.page -
				2);
			let end = Math.min(result.page + (result.count - 1), result.totalPage);
			for (let i = start; i <= end; i++) {
				result.pages.push(i);
				if (result.pages.length >= result.count) {
					break;
				}
			}
			console.log(result);

			return result;
		}
	},
	template: `<div class="cl-cantainer container">
				<div class="row">
					<div class="col-md-9 cl-left">

						<div class="cl-card" v-for="item in articleList">
							<div class="row">
								<div class="col-lg-3 col-md-4 col-sm-12 cl-card-image" v-if="item.cover_image">
									<a :href="'calmlog-details.html?article_id='+item.article_id">
										<img :src="item.cover_image" class="img-fluid" alt="">
									</a>
								</div>
								<div class="col-lg-9 col-md-8 col-sm-12 cl-card-main">
									<h3 class="cl-card-main-title"><a :href="'calmlog-details.html?article_id='+item.article_id">
											{{item.article_title}} </a></h3>
									<p class="cl-card-main-info">{{ item.intro }}</p>
									<p class="cl-card-more">
										<a :href="'calmlog-details.html?article_id='+item.article_id">阅读更多...</a>
									</p>
								</div>
							</div>
						</div>

						<nav aria-label="Page navigation example">
							<ul class="pagination justify-content-center">
								<li class="page-item" :class="{disabled: paginator.page==1}">
									<a class="page-link"
									   aria-label="Previous"
									   :href="'#page='+(paginator.page-1)"
									   @click="getArticleList(paginator.page-1)"
									>
										<span aria-hidden="true">&laquo;</span>
										<span class="sr-only">Previous</span>
									</a>
								</li>
			
								<li v-for="item in paginator.pages"
									class="page-item"
									:class="{active:paginator.page==item}"
									@click="getArticleList(item)"
								><a class="page-link" :href="'#page='+item">{{ item }}</a>
								</li>
			
								<li class="page-item" :class="{disabled: paginator.page==paginator.totalPage}">
									<a class="page-link" :href="'#page='+(paginator.page+1)" aria-label="Next"
									   @click="getArticleList(paginator.page+1)"
									>
										<span aria-hidden="true">&raquo;</span>
										<span class="sr-only">Next</span>
									</a>
								</li>
							</ul>
						</nav>

					</div>
					
					<co-middle-right></co-middle-right>
					
				</div>

			</div>
	`
});

Vue.component('co-middle-detail', {
	data: function() {
		return {
			articleId: 0,
			commentLength: 0,
			article: {
				article_title: "article_title",
				add_time: 0,
				content: "content"
			}
		};
	},
	created: function() {
		this.articleId = getQueryParam('article_id', 0);
		let _this = this;

		axios.get('http://localhost:8901/api/article/detail/?article_id=' + this.articleId)
			.then(function(response) {
				if (response.data.status == 0) { // 服务端成功处理
					_this.article = response.data.data.article;
					// app.categoryId = _this.article.category_id;
					_this.$parent.categoryId = _this.article.category_id;
					// console.log(_this.article);
				} else {
					alert("获取文章失败，具体信息：" + response.data.message);
				}
			})
			.catch(function(error) {
				console.log(error);
			});
	},
	filters: {
		formatTime: formatTime
	},
	template: `
			<div class="cl-cantainer container">
				<div class="row">
					<div class="col-md-9 cl-left">
						<div class="cl-artical-content">
							<h2 class="cl-artical-title">{{ article.article_title }}</h2>
							<div class="cl-card-tag">
								<div><span>{{ commentLength }}</span>人评论 /
									发布时间：<span>{{ article.add_time | formatTime }}</span>
								</div>
							</div>
							<div class="cl-artical" v-html="article.content"></div>
						</div>

						<co-comment></co-comment>

					</div>

					<co-middle-right></co-middle-right>
					
				</div>
			</div>
`
});

Vue.component('co-comment', {
	data: function() {
		return {
			articleId: 0,
			commentList: [{
				nickname: '11',
				add_time: 1624926634,
				comment_content: '2222'
			}],
			comment: {
				article_id: 0,
				comment_content: '',
				nickname: '',
				email: ''
			}
		};
	},
	filters: {
		formatTime: formatTime
	},
	created: function() {
		this.articleId = getQueryParam('article_id', 0);
		this.comment.article_id = this.articleId;
		let _this = this;

		axios.get('http://localhost:8901/api/comment/list/?article_id=' + this.articleId)
			.then(function(response) {
				if (response.data.status == 0) { // 服务端成功处理
					_this.commentList = response.data.data.commentList;
				} else {
					alert("获取评论失败，具体信息：" + response.data.message);
				}
			})
			.catch(function(error) {
				console.log(error);
			});
	},
	methods: {
		addComment: function() {
			let _this = this;

			let params = new URLSearchParams();
			for (let i in _this.comment) {
				params.append(i, _this.comment[i]);
			}
			axios.post("http://localhost:8901/api/comment/add/", params)
				.then(function(response) {
					console.log(response);
					if (response.data.status == 0) { // 服务端成功处理
						_this.commentList.unshift(response.data.data.comment);
						_this.comment.nickname = '';
						_this.comment.email = '';
						_this.comment.comment_content = '';
						// _this.comment = _this.commentTpl;
					} else {
						alert("增加评论失败，具体信息：" + response.data.message);
					}
				}).catch(function(error) {
					console.log(error);
				});
		}
	},
	template: `<div class="comment">

				<form class="cl-comment-from">
					<input type="hidden" id="article_id" v-model="comment.article_id">
					<div>
						<textarea id="comment_content" placeholder="说点什么吧..." rows="2" v-model="comment.comment_content"></textarea>
					</div>
					<input id="email" type="text" placeholder="邮箱" v-model="comment.email">
					<input id="nickname" type="text" placeholder="昵称" v-model="comment.nickname">
					<button type="button" id="comment-btn" v-on:click="addComment()">留言</button>
					<span class="clearfix"></span>
				</form>

				<h4 class="right-card-title">全部评论</h4>
				
				<div class="comment-panel" v-for="item in commentList">
					<div class="comment-panel-portrait">
						<img src="img/portrait.png" class="img-fluid rounded-circle" alt="">
					</div>
					<div class="comment-panel-content">
						<div class="comment-panel-content-item">
							<div class="comment-author">{{ item.nickname }}</div>
							<div>{{ item.add_time | formatTime }}</div>
						</div>
						<div class="comment-panel-content-main">{{ item.comment_content }}</div>
					</div>
					<span class="clearfix"></span>
					<div class="text-primary"><a href="">回复</a></div>
				</div>

			</div>`
});

Vue.component('co-middle-right', {
	template: `<div class="col-md-3 cl-right">
						<div class="right-card">

							<div class="right-card-main">
								<div class="right-card-title">个人微信号</div>
								<div class="cl-code">
									<img src="temporary-img/code.jpg" class="img-fluid" alt="">
									<p>关注作者获取更多模板信息，定时发布干货文章</p>
								</div>

							</div>
						</div>

					</div>`
});

Vue.component('co-footer', {
	template: `<div class="container-fluid cl-footer">
				<div class="container">
					<p class="cl-copyright">本设计由简.工作室荣誉出品</p>
					<p class="cl-copyright">copyright @ 2017~2018 简.工作室（www.jeanstudio.cn）</p>
				</div>
			</div>
`
});

let app = new Vue({
	el: "#app",
	data: {
		categoryId: 0
	}
});
